import request from 'request-promise'
import _ from 'lodash'
import fs from 'fs'
import cookie from 'cookie'
var crypto = require('crypto')
function md5 (text) {
  return crypto.createHash('md5').update(text).digest('hex')
}
async function uploadFileApi (ctx) {
  if (ctx.url === '/api/course/previewvideos/uploadOnlyVideo') {
    const { files } = ctx.request.body
    if (!files || _.isEmpty(files)) {
      return false
    }
    const filesKey = Object.keys(files)
    const file = files[filesKey].path
    return {
      [filesKey]: fs.createReadStream(file)
    }
  }
  return null
}
export default async function (ctx, next) {
  if (/mock/.test(ctx.url)) {
    ctx.type = 'json'
    const data = {
      success: true
    }
    if (ctx.method === 'POST') {
      data.from = ctx.request.body
    }
    ctx.body = data
  }
  if (/api/.test(ctx.url)) {
    let options = {
      method: ctx.method,
      url: 'http://120.27.17.206:8000' + ctx.url.replace(/^\/api(?=\/)/g, ''),
      headers: {},
      json: true
    }
    if (ctx.headers['cookie']) {
      var cookies = cookie.parse(ctx.headers['cookie'])
      var token = cookies.token
      var userId = cookies.id
      if (token) {
        options.headers['token'] = token
        options.headers['userId'] = userId
      }
    }
    if (ctx.method === 'POST' || ctx.method === 'PUT') {
      if (ctx.url === '/api/user/password/current' && ctx.request.body.oldPassword) {
        ctx.request.body.oldPassword = md5(ctx.request.body.oldPassword)
      }
      var file = await uploadFileApi(ctx)
      if (file) {
        options.formData = Object.assign(file, ctx.request.body.fields)
        options.headers['content-type'] = 'multipart/form-data'
      } else {
        options.headers['content-type'] = 'application/json'
        options = Object.assign(options, {
          body: ctx.request.body
        })
      }
    }
    let body
    try {
      body = await request(options)
    } catch (e) {
      body = {
        success: false
      }
    }
    ctx.body = body
    return
  }
  await next()
}
